package com.itheima.day3.stream;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

// Collector 收集器
public class C12CollectorTest {
    record Hero(String name, int strength) {

    }

    public static void main(String[] args) {
        Stream<String> stream = Stream.of("令狐冲", "风清扬", "独孤求败", "方证",
                "东方不败", "冲虚", "向问天", "任我行", "不戒");

        // 1) 收集到 List
        List<String> result = stream.collect(() -> new ArrayList<>(), (list, x) -> list.add(x), (a, b) -> {
        });
        List<String> result2 = stream.collect(ArrayList::new, ArrayList::add, (a, b) -> {
        });

        List<String> result3 = stream.collect(Collectors.toList());
        List<String> result4 = stream.toList();

        // 2) 收集到 Set
        Set<String> result5 = stream.collect(LinkedHashSet::new, Set::add, (a, b) -> {
        });
        Set<String> result6 = stream.collect(Collectors.toSet());

        // 3)收集到 StringBuilder
        StringBuilder sb = stream.collect(StringBuilder::new, StringBuilder::append, (a, b) -> {
        });
        String result7 = stream.collect(Collectors.joining());

        // 4) 收集到 StringJoiner
        StringJoiner sj = stream.collect(() -> new StringJoiner(","), StringJoiner::add, (a, b) -> {
        });
        String result8 = stream.collect(Collectors.joining(","));

        // 5) 收集到 Map (key、value)
        Map<String, Integer> result9 = stream.collect(HashMap::new, (map, x) -> map.put(x, 1), (a, b) -> {
        });
        Map<String, Integer> map = stream.collect(Collectors.toMap(x -> x, x -> 1));

        /*
            Map
            2: new ArrayList(["方证","冲虚","不戒"])
            3: new ArrayList(["令狐冲","风清扬","向问天","任我行"])
            4: new ArrayList(["独孤求败","东方不败"])

            下游收集器
         */
        // 按元素长度分组收集
        Map<Integer, List<String>> result10 = stream.collect(Collectors.groupingBy(String::length, Collectors.toList()));

        // 按元素长度分组收集，并将元素使用逗号分隔
        Map<Integer, String> result11 = stream.collect(Collectors.groupingBy(String::length, Collectors.joining(",")));
        for (Map.Entry<Integer, String> e : result11.entrySet()) {
            System.out.println(e);
        }
    }
}
